/**
 * @description user API 路由
 * @author malin
 */

const router = require('koa-router')()
const { 
    isExist, 
    register, 
    login, 
    deleteCurrUser, 
    changeInfo,
    changePassword,
    logout
} = require('../../controller/user')
const { isTest } = require('../../utils/env')
const { loginCheck } = require('../../middlewares/loginChecks')

const userValidate = require('../../validator/user')
const { genValidator } = require('../../middlewares/validator')
const { getFollowers } = require('../../controller/user-relation')

router.prefix('/api/user')

// 用户注册（校验用户数据）
router.post('/register',genValidator(userValidate), async (ctx, next) => {
    const { userName, password, gender } = ctx.request.body
    // 调用controller
    ctx.body = await register({ 
        // 传参顺序不限
        userName, 
        password, 
        gender 
    })
})

// 判断用户是否存在
router.post('/isExist', async (ctx, next) => {
    // 路由只管路由的派发，参数的获取，以及http响应
    const { userName } = ctx.request.body
    // 调用controller里的内容
    ctx.body = await isExist(userName)
})

// 用户登录
router.post('/login', async (ctx, next) => {
    const { userName, password } = ctx.request.body
    // 调用controller
    ctx.body = await login({ userName, password, ctx })
})

// 删除用户（仅测试环境下删除，且先登录再删除）
router.post('/delete',loginCheck, async (ctx, next) => {
    if(isTest) {
        // 测试环境下，测试账号登录之后删除自己（不能删除别人）
        const { userName } = ctx.session.userInfo
        // 调用controller
        ctx.body = await deleteCurrUser(userName)
    }
})

// 修改个人信息（格式验证）
router.patch('/changeInfo',loginCheck, genValidator(userValidate), async (ctx, next) => {
    const { nickName, city, picture } = ctx.request.body
    // controller
    ctx.body = await changeInfo(ctx, { nickName, city, picture })
})

// 修改用户密码（格式验证）
router.patch('/changePassword', loginCheck, genValidator(userValidate), async (ctx, next) => {
    const { password, newPassword } = ctx.request.body
    const { userName } = ctx.session.userInfo
    // controller
    ctx.body = await changePassword({ userName, password, newPassword })
})

// 退出登录
router.post('/logout', loginCheck, async (ctx, next) => {
    // controller
    ctx.body = await logout(ctx)
})

// 获取@列表，即关注人列表
router.get('/getAtList', loginCheck, async (ctx, next) => {
    const { id: userId } = ctx.session.userInfo
    // controller
    const result = await getFollowers(userId)
    const { followersList } = result.data
    const list = followersList.map(user => {
        return `${user.nickName} - ${user.userName}`
    })
    ctx.body = list
})

module.exports = router


